/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gestores;

import ferramentas.Seguranca;
import java.io.IOException;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sistema.Utilizador;

/**
 *
 * @author Tshuba
 */
public class Gestor extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        String gestor = request.getParameter("gestor");

        if (gestor.equals(Gestor.UTILIZADORES)) {
            getServletConfig().getServletContext().
                    getRequestDispatcher("/GestorUtilizadores").forward(request, response);
        } else if (gestor.equals(Gestor.COLABORADORES)) {
            getServletConfig().getServletContext().
                    getRequestDispatcher("/GestorDeColaboradores").forward(request, response);
        } else if (gestor.equals(Gestor.LOGIN)) {
            login(request, response);
        } else if (gestor.equals(Gestor.APOSTA)) {
            getServletConfig().getServletContext().
                    getRequestDispatcher("/GestorAposta").forward(request, response);
        } else {
            IllegalArgumentException illegal_argument_exception = new IllegalArgumentException();
            session.setAttribute("excepcao", illegal_argument_exception.toString());
            response.sendRedirect("/Projecto_PR/mostra_erro.jsp");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        if (devolveTabelaDeErrosParaLogin(request).isEmpty()) {
            String email = request.getParameter("email");
            String password = Seguranca.converteParaMD5(request.getParameter("password"));
            try {
                if (Utilizador.existeEmail(email)) {
                    if (Utilizador.eValida(email, password)) {
                        // Set maximum inactive interval permited by the server
                        session.setMaxInactiveInterval(500);
                        session = request.getSession();
                        session.setAttribute("session_id", session.getId());
                        Utilizador user = Utilizador.devolvePorEmail(email);
                        session.setAttribute("perfil", user.getPerfil());
                        if (user.getPerfil().equals("utilizador")) {
                            session.setAttribute("label_bem_vindo", user.getNome());
                            session.setAttribute("utilizador", user);
                            response.sendRedirect("/Projecto_PR/area_cliente.jsp");
                        } else if (user.getPerfil().equals("colaborador")) {
                            session.setAttribute("label_bem_vindo", user.getNome());
                            response.sendRedirect("/Projecto_PR/area_colaborador.jsp");
                        } else {
                            response.sendRedirect("/Projecto_PR/login.jsp");
                        }
                    } else {
                        Hashtable<String, String> erros = new Hashtable<String, String>();
                        erros.put("password", "password não está correcta.");
                        session.setAttribute("campos_invalidos", erros);
                        response.sendRedirect("/Projecto_PR/login.jsp");
                    }
                } else {
                    Hashtable<String, String> erros = new Hashtable<String, String>();
                    erros.put("email", "Username não existe.");
                    session.setAttribute("campos_invalidos", erros);
                    response.sendRedirect("/Projecto_PR/login.jsp");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                response.sendRedirect("/Projecto_PR/login.jsp");
            }
        } else {
            session.setAttribute("campos_invalidos", devolveTabelaDeErrosParaLogin(request));
            response.sendRedirect("/Projecto_PR/login.jsp");
        }
    }

    private Hashtable<String, String> devolveTabelaDeErrosParaLogin(final HttpServletRequest request) {

        Hashtable<String, String> tabela_de_erros = new Hashtable<String, String>();
        String email = request.getParameter("email");



        if (email == null || email.trim().equals("")) {
            tabela_de_erros.put("email", "Campo Obrigatório. Não pode estar vazio.");


        } else if (email.length() < 6) {
            tabela_de_erros.put("email", "Tamanho inválido. O campo email deverá ter pelo menos 6 caracteres.");


        }

        String password = (String) request.getParameter("password");



        if (password == null || password.trim().equals("")) {
            tabela_de_erros.put("password", "Campo Obrigatório. Não pode estar vazio.");


        }
        if (password != null && !password.trim().equals("") && password.length() < 6) {
            tabela_de_erros.put("password", "Tamanho inválido. O campo password deverá ter pelo menos 6 caracteres.");


        }
        return tabela_de_erros;


    }
    public static final String UTILIZADORES = "gestor_de_utilizadores";
    public static final String COLABORADORES = "gestor_de_colaboradores";
    public static final String APOSTA = "gestor_de_aposta";
    public static final String LOGIN = "gestor_login";
}
